package com.iseastar.guojiang.transfer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.loc.BaiduLocationService;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.TransferInfoBean;
import com.iseastar.guojiang.model.TransferTodayParcelBean;
import com.iseastar.guojiang.newcabinet.BikingRouteOverlay;
import com.iseastar.guojiang.newcabinet.TaskCaptureActivity;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;

import droid.frame.utils.lang.Str;

/**
 * 卫星仓管理
 * Created by lidandan on 2018/1/27.
 */
public class TaskSatelliteWarehouseActivity extends BaseActivity2 implements View.OnClickListener {

    private TextView mJunctionPointTimeTV;//交接时间
    private BaiduMap mBaiduMap;
    private TextureMapView mMapView = null;

    private PlanNode sNode = null;
    private PlanNode eNode = null;
    private RoutePlanSearch mSearch;

    private View mMyLocationMarkerView = null;
    private TransferInfoBean infoBean = null;
    private double transferLat = 0;
    private double transferLon = 0;
    private double myLat = 0;
    private double myLon = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog("正在定位");
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.putExtra("msgId", MsgID.get_task_satellite_warehouse_location);
        startService(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mMapView.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.task_satellite_warehouse);
        super.findViewById();
        getAppTitle().setCommonTitle("卫星仓管理");
        mJunctionPointTimeTV = (TextView) findViewById(R.id.junction_point_time_tv);
        findViewById(R.id.modify_junction_point_btn).setOnClickListener(this);
        findViewById(R.id.scan_courier_qrcode_btn).setOnClickListener(this);
        findViewById(R.id.today_send_parcel_btn).setOnClickListener(this);
        initMapView();
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(listener);
    }


    private void initMapView() {
        // 地图初始化
        mMapView = (TextureMapView) findViewById(R.id.bmapView);
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(false);//隐藏比例尺
        int count = mMapView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mMapView.getChildAt(i);
            // 隐藏缩放按键 ZoomControl
            if (child instanceof ImageView || child instanceof ZoomControls) {
                child.setVisibility(View.INVISIBLE);
            }
        }
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //修改交接时间
            case R.id.modify_junction_point_btn:
                DialogMgr.courierSelectTransferTime(TaskSatelliteWarehouseActivity.this, findViewById(R.id.today_send_parcel_btn), mJunctionPointTimeTV.getText().toString());
                break;
            //扫码火箭侠二维码
            case R.id.scan_courier_qrcode_btn:
                Intent intent = new Intent(getContext(), TaskCaptureActivity.class);
                intent.setAction(Intents.courier_scan_for_tansfer);
                startActivityForResult(intent, Const.RequestCode.courier_scan_task);
                break;
            //今日揽收包裹
            case R.id.today_send_parcel_btn:
                startActivity(TransferTodayParcelListActivity.class);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.get_task_satellite_warehouse_location:
                cancelLoadingDialog();
                final BDLocation loc = (BDLocation) msg.obj;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loc == null) {
                            showToast("定位失败");
                        } else {
                            String currentCityName = loc.getCity();
                            if (isNotEmpty(currentCityName)) {
                                myLat = loc.getLatitude();
                                myLon = loc.getLongitude();
                                showLoadingDialog("正在查询卫星仓");
                                AppHttp.getInstance().courierSatelliteWareInfo();
                            } else {
                                showToast("定位失败");
                            }
                        }
                    }
                });
                return false;
            //扫描二维码查询交接详情
            case MsgID.task_satellite_warehouse_qr_code:
                cancelLoadingDialog();
                ReqResult<TransferTodayParcelBean> result = JSON.parser(msg.obj, TransferTodayParcelBean.class);
                if (checkLoginStatus(result)) {
                    TransferTodayParcelBean parcel = result.getResult();
                    if (parcel != null && parcel.getParcelDtos() != null && parcel.getParcelDtos().size() > 0) {
                        Intent intent = new Intent(TaskSatelliteWarehouseActivity.this, ParcelHandoverDetailsListActivity.class);
                        intent.putExtra("item", parcel);
                        startActivity(intent);
                    } else {
                        showToast("该火箭侠暂无包裹！");
                    }
                } else {
                    showToast(result.getMessage());
                }
                return true;
            //卫星仓管理数据信息返回
            case MsgID.courier_satellite_warehouse_info:
                cancelLoadingDialog();
                ReqResult<TransferInfoBean> resultInfo = JSON.parser(msg.obj, TransferInfoBean.class);
                if (checkLoginStatus(resultInfo)) {
                    infoBean = resultInfo.getResult();
                    if (infoBean != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                transferLat = infoBean.getBdLatitude();
                                transferLon = infoBean.getBdLongitude();
                                addMarkToMap(transferLat, transferLon, myLat, myLon);
                                ((TextView) findViewById(R.id.junction_point_tv)).setText(infoBean.getWareHouseName() + "-包裹交接点");
                                ((TextView) findViewById(R.id.junction_point_postal_tv)).setText(infoBean.getAddress());
                                if (isNotEmpty(infoBean.getTransStart()) && isNotEmpty(infoBean.getTransEnd())) {
                                    mJunctionPointTimeTV.setText(infoBean.getTransStart() + "-" + infoBean.getTransEnd());
                                }
                            }
                        });
                    } else {
                        showToast("服务器数据异常");
                    }
                } else {
                    showToast(resultInfo.getMessage());
                }
                return true;
            //修改卫星仓交接时间
            case MsgID.courier_satellite_warehouse_update_time:
                cancelLoadingDialog();
                ReqResult<TransferInfoBean> reqResult = JSON.parser(msg.obj, TransferInfoBean.class);
                if (checkLoginStatus(reqResult)) {
                    infoBean = reqResult.getResult();
                    if (infoBean != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                transferLat = infoBean.getBdLatitude();
                                transferLon = infoBean.getBdLongitude();
                                if (isNotEmpty(infoBean.getTransStart()) && isNotEmpty(infoBean.getTransEnd())) {
                                    mJunctionPointTimeTV.setText(infoBean.getTransStart() + "-" + infoBean.getTransEnd());
                                }
                                addMarkToMap(transferLat, transferLon, myLat, myLon);
                            }
                        });
                    } else {
                        showToast("服务器数据异常");
                    }
                } else {
                    showToast(reqResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 用于添加火箭侠的位置和仓的位置
     */
    private void addMarkToMap(double transferLat, double transferLon, double myLat, double myLon) {
        if (transferLat > 0 && transferLon > 0 && myLat > 0 && myLon > 0) {
            mMapView.getMap().clear();
            sNode = PlanNode.withLocation(new LatLng(myLat, myLon));
            eNode = PlanNode.withLocation(new LatLng(transferLat, transferLon));
            LatLng northeast = new LatLng(Math.max(transferLat, myLat), Math.max(transferLon, myLat));
            LatLng southwest = new LatLng(Math.min(transferLat, myLat), Math.min(transferLon, myLat));
            LatLngBounds bounds = new LatLngBounds.Builder().include(northeast).include(southwest).build();
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(bounds);
            double distance = Double.parseDouble(Str.formatDoubleData(DistanceUtil.getDistance(new LatLng(transferLat, transferLon), new LatLng(myLat, myLon))));
            mMyLocationMarkerView = LayoutInflater.from(getContext()).inflate(R.layout.layout_task_rocket_man_tip, null, false);
            if (distance <= 100) {
                ((TextView) mMyLocationMarkerView.findViewById(R.id.distance_tv)).setText("已就位");
            } else {
                ((TextView) mMyLocationMarkerView.findViewById(R.id.distance_tv)).setText("离仓还有" + distance + "米");
            }
            if (sNode != null && eNode != null) {
                mSearch.bikingSearch((new BikingRoutePlanOption()).from(sNode).to(eNode));
            }
        }
    }

    OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult result) {
            //获取步行线路规划结果
        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult result) {
            //获取公交换乘路径规划结果
        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult result) {
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
            if (bikingRouteResult == null || bikingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                //result.getSuggestAddrInfo()
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
                BikingRouteOverlay overlay = new MyBikingRouteOverlay(mBaiduMap);//路线覆盖物，MyDrivingRouteOverlay代码下面给出
                //            mBaidumap.setOnMarkerClickListener(overlay);
                overlay.setData(bikingRouteResult.getRouteLines().get(0));
                overlay.addToMap();
                overlay.zoomToSpan();
            }
        }
    };

    private class MyBikingRouteOverlay extends BikingRouteOverlay {
        /**
         * 构造函数
         *
         * @param baiduMap 该DrivingRouteOvelray引用的 BaiduMap
         */
        public MyBikingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            //覆写此方法以改变默认起点图标
            return BitmapDescriptorFactory.fromView(mMyLocationMarkerView);
            //这里可以使用BitmapDescriptorFactory.fromView(view)实现自定义view覆盖物，自定义覆盖物请关注以后的文章。
        }

        @Override
        public Integer getLineColor() {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认绘制颜色
            //Returns:
            //线颜色
            return getResources().getColor(R.color.transparent);
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            //覆写此方法以改变默认终点图标
            return BitmapDescriptorFactory.fromResource(R.drawable.transfer_location_red_icon);
        }

        @Override
        public boolean onRouteNodeClick(int i) {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认点击处理
            return true;
        }
    }

    /**
     * 完成时间选择进行展示
     *
     * @param timeStr
     */
    public void finishSelectTime(String timeStr) {
        if (isNotEmpty(timeStr) && infoBean != null) {
            showLoadingDialog(null);
            AppHttp.getInstance().courierSatelliteWareUpdateTime(infoBean.getId(), timeStr.split("-")[0], timeStr.split("-")[1]);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //扫描二维码返回的数据
        if (resultCode == Activity.RESULT_OK && Const.RequestCode.courier_scan_task == requestCode) {
            String result = data.getStringExtra("result");
            if (StringUtils.isEmpty(result)) {
                return;
            }
            int index = result.lastIndexOf("=");
            String result2;
            if (index > -1) {
                result2 = result.substring(index + 1, result.length());
            } else {
                result2 = result;
            }
            showLoadingDialog(null);
            AppHttp.getInstance().taskSatelliteWarehouseQRCode(result2);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mSearch != null) {
            mSearch.destroy();
        }
        if (mBaiduMap != null) {
            mBaiduMap.clear();
        }
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
        super.onDestroy();
    }
}
